//! # 增强 Metrics 功能演示
//! 
//! 此示例展示了 RustCloud 增强指标收集功能，包括：
//! * 企业级 Prometheus 集成
//! * APM 性能监控
//! * 自定义指标收集
//! * HTTP 服务器 /metrics 端点

use rustcloud_metrics::{
    EnhancedMetricsCollector, 
    EnhancedCollectorConfig,
    EnhancedPrometheusExporter,
    PrometheusConfig,
    SystemMetricsCollector,
    CustomCollector,
    MetricDescriptor,
    MetricFamily,
    MetricType,
    MetricsCollector
};\nuse std::collections::HashMap;\nuse std::sync::Arc;\nuse std::time::Duration;\nuse tokio::time::{sleep, interval};\nuse tracing::{info, error};\n\n#[tokio::main]\nasync fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {\n    // 初始化日志\n    tracing_subscriber::init();\n    info!(\"🚀 启动 RustCloud 增强 Metrics 演示\");\n\n    // 创建增强的指标收集器\n    let collector_config = EnhancedCollectorConfig {\n        enable_http_metrics: true,\n        enable_jvm_metrics: true,\n        enable_app_metrics: true,\n        metric_retention: 3600,\n        max_metrics: 10000,\n        aggregation_interval: 15,\n        enable_sampling: false,\n        sampling_rate: 1.0,\n        default_histogram_buckets: vec![\n            0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, f64::INFINITY\n        ],\n        default_summary_quantiles: vec![0.5, 0.9, 0.95, 0.99],\n    };\n    \n    let collector = Arc::new(EnhancedMetricsCollector::new(collector_config));\n    \n    // 设置应用信息\n    collector.set_app_info(\"app_name\".to_string(), \"rustcloud-demo\".to_string()).await?;\n    collector.set_app_info(\"version\".to_string(), \"1.0.0\".to_string()).await?;\n    collector.set_app_info(\"environment\".to_string(), \"development\".to_string()).await?;\n    \n    // 创建 Prometheus 导出器\n    let mut prometheus_config = PrometheusConfig::default();\n    prometheus_config.port = 9090;\n    prometheus_config.global_labels.insert(\"service\".to_string(), \"rustcloud-demo\".to_string());\n    prometheus_config.global_labels.insert(\"instance\".to_string(), \"localhost:9090\".to_string());\n    \n    let exporter = Arc::new(EnhancedPrometheusExporter::new(collector.clone(), prometheus_config));\n    \n    // 注册系统指标收集器\n    let system_collector = Arc::new(SystemMetricsCollector::new());\n    exporter.register_collector(system_collector).await?;\n    \n    // 注册自定义业务指标收集器\n    let business_collector = Arc::new(BusinessMetricsCollector::new());\n    exporter.register_collector(business_collector).await?;\n    \n    // 设置自定义直方图桶\n    exporter.set_histogram_buckets(\n        \"http_request_duration_seconds\", \n        vec![0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, f64::INFINITY]\n    ).await?;\n    \n    // 启动指标生成任务\n    let collector_clone = collector.clone();\n    tokio::spawn(async move {\n        generate_sample_metrics(collector_clone).await;\n    });\n    \n    // 启动定期清理任务\n    let exporter_clone = exporter.clone();\n    tokio::spawn(async move {\n        let mut cleanup_interval = interval(Duration::from_secs(60));\n        loop {\n            cleanup_interval.tick().await;\n            if let Err(e) = exporter_clone.cleanup_cache().await {\n                error!(\"清理缓存失败: {}\", e);\n            }\n        }\n    });\n    \n    // 启动 HTTP 服务器\n    info!(\"📊 Prometheus metrics 服务器启动在 http://localhost:9090/metrics\");\n    info!(\"📈 指标统计信息可通过 http://localhost:9090/metrics/stats 获取\");\n    \n    exporter.start_server().await?;\n    \n    Ok(())\n}\n\n/// 生成示例指标数据\nasync fn generate_sample_metrics(collector: Arc<EnhancedMetricsCollector>) {\n    let mut interval = interval(Duration::from_secs(5));\n    let mut request_count = 0;\n    \n    loop {\n        interval.tick().await;\n        request_count += 1;\n        \n        // 模拟 HTTP 请求指标\n        let methods = [\"GET\", \"POST\", \"PUT\", \"DELETE\"];\n        let paths = [\"/api/users\", \"/api/orders\", \"/api/products\", \"/health\"];\n        let statuses = [200, 201, 400, 404, 500];\n        \n        for &method in &methods {\n            for &path in &paths {\n                for &status in &statuses {\n                    let duration = Duration::from_millis(fastrand::u64(10..500));\n                    \n                    if let Err(e) = collector.record_http_request(method, path, status, duration).await {\n                        error!(\"记录 HTTP 请求指标失败: {}\", e);\n                    }\n                }\n            }\n        }\n        \n        // 模拟数据库查询指标\n        let operations = [\"SELECT\", \"INSERT\", \"UPDATE\", \"DELETE\"];\n        let tables = [\"users\", \"orders\", \"products\"];\n        \n        for &operation in &operations {\n            for &table in &tables {\n                let duration = Duration::from_millis(fastrand::u64(1..100));\n                let success = fastrand::f64() > 0.1; // 90% 成功率\n                \n                if let Err(e) = collector.record_database_query(operation, table, duration, success).await {\n                    error!(\"记录数据库查询指标失败: {}\", e);\n                }\n            }\n        }\n        \n        // 模拟缓存操作指标\n        let cache_operations = [\"get\", \"set\", \"delete\"];\n        let cache_names = [\"user_cache\", \"session_cache\", \"product_cache\"];\n        \n        for &operation in &cache_operations {\n            for &cache_name in &cache_names {\n                let hit = fastrand::f64() > 0.2; // 80% 命中率\n                \n                if let Err(e) = collector.record_cache_operation(operation, cache_name, hit).await {\n                    error!(\"记录缓存操作指标失败: {}\", e);\n                }\n            }\n        }\n        \n        // 模拟连接数变化\n        if request_count % 3 == 0 {\n            collector.inc_active_connections();\n        } else if request_count % 7 == 0 {\n            collector.dec_active_connections();\n        }\n        \n        // 记录一些自定义业务指标\n        let mut labels = HashMap::new();\n        labels.insert(\"region\".to_string(), \"us-west-1\".to_string());\n        \n        // 用户注册数\n        if let Ok(counter) = collector.counter(\"user_registrations_total\", \"Total user registrations\", labels.clone()).await {\n            if fastrand::f64() > 0.7 {\n                counter.inc();\n            }\n        }\n        \n        // 订单金额\n        if let Ok(histogram) = collector.histogram(\n            \"order_amount_dollars\", \n            \"Order amount in dollars\", \n            labels.clone(),\n            Some(vec![10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, f64::INFINITY])\n        ).await {\n            let amount = fastrand::f64() * 1000.0;\n            histogram.observe(amount);\n        }\n        \n        // 当前在线用户数\n        if let Ok(gauge) = collector.gauge(\"current_online_users\", \"Current number of online users\", labels).await {\n            let change = (fastrand::f64() - 0.5) * 10.0;\n            gauge.add(change);\n        }\n        \n        info!(\"📊 生成了第 {} 轮指标数据\", request_count);\n    }\n}\n\n/// 自定义业务指标收集器\nstruct BusinessMetricsCollector {\n    enabled: bool,\n}\n\nimpl BusinessMetricsCollector {\n    fn new() -> Self {\n        Self { enabled: true }\n    }\n}\n\n#[async_trait::async_trait]\nimpl CustomCollector for BusinessMetricsCollector {\n    fn name(&self) -> &str {\n        \"business\"\n    }\n\n    fn describe(&self) -> Vec<MetricDescriptor> {\n        vec![\n            MetricDescriptor {\n                name: \"business_revenue_total\".to_string(),\n                help: \"Total business revenue in dollars\".to_string(),\n                metric_type: MetricType::Counter,\n                labels: vec![\"product_category\".to_string()],\n            },\n            MetricDescriptor {\n                name: \"business_customer_satisfaction\".to_string(),\n                help: \"Customer satisfaction score\".to_string(),\n                metric_type: MetricType::Gauge,\n                labels: vec![\"department\".to_string()],\n            },\n        ]\n    }\n\n    async fn collect(&self) -> Result<Vec<MetricFamily>, Box<dyn std::error::Error + Send + Sync>> {\n        if !self.enabled {\n            return Ok(vec![]);\n        }\n\n        let mut families = Vec::new();\n\n        // 业务收入指标\n        let revenue_family = MetricFamily {\n            name: \"business_revenue_total\".to_string(),\n            help: \"Total business revenue in dollars\".to_string(),\n            metric_type: MetricType::Counter,\n            metrics: vec![\n                rustcloud_metrics::Metric {\n                    name: \"business_revenue_total\".to_string(),\n                    help: \"Total business revenue in dollars\".to_string(),\n                    metric_type: MetricType::Counter,\n                    value: rustcloud_metrics::MetricValue::Counter(125000.0),\n                    labels: {\n                        let mut labels = HashMap::new();\n                        labels.insert(\"product_category\".to_string(), \"electronics\".to_string());\n                        labels\n                    },\n                    timestamp: std::time::SystemTime::now(),\n                },\n                rustcloud_metrics::Metric {\n                    name: \"business_revenue_total\".to_string(),\n                    help: \"Total business revenue in dollars\".to_string(),\n                    metric_type: MetricType::Counter,\n                    value: rustcloud_metrics::MetricValue::Counter(87500.0),\n                    labels: {\n                        let mut labels = HashMap::new();\n                        labels.insert(\"product_category\".to_string(), \"clothing\".to_string());\n                        labels\n                    },\n                    timestamp: std::time::SystemTime::now(),\n                },\n            ],\n        };\n        families.push(revenue_family);\n\n        // 客户满意度指标\n        let satisfaction_family = MetricFamily {\n            name: \"business_customer_satisfaction\".to_string(),\n            help: \"Customer satisfaction score\".to_string(),\n            metric_type: MetricType::Gauge,\n            metrics: vec![\n                rustcloud_metrics::Metric {\n                    name: \"business_customer_satisfaction\".to_string(),\n                    help: \"Customer satisfaction score\".to_string(),\n                    metric_type: MetricType::Gauge,\n                    value: rustcloud_metrics::MetricValue::Gauge(4.2),\n                    labels: {\n                        let mut labels = HashMap::new();\n                        labels.insert(\"department\".to_string(), \"sales\".to_string());\n                        labels\n                    },\n                    timestamp: std::time::SystemTime::now(),\n                },\n                rustcloud_metrics::Metric {\n                    name: \"business_customer_satisfaction\".to_string(),\n                    help: \"Customer satisfaction score\".to_string(),\n                    metric_type: MetricType::Gauge,\n                    value: rustcloud_metrics::MetricValue::Gauge(4.5),\n                    labels: {\n                        let mut labels = HashMap::new();\n                        labels.insert(\"department\".to_string(), \"support\".to_string());\n                        labels\n                    },\n                    timestamp: std::time::SystemTime::now(),\n                },\n            ],\n        };\n        families.push(satisfaction_family);\n\n        Ok(families)\n    }\n\n    fn is_enabled(&self) -> bool {\n        self.enabled\n    }\n}